package kryptologieBlatt1;
import java.awt.Container;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class Vigenere {
	
	private String alphabet;
	private String key;
	private String plainText;
	private int periode;
		
	public Vigenere() {
		initVariables();
	}
	
	public String tryToDecodeChiffre(String chiffreText){
		fetchPeriode(chiffreText);
		fetchKey(chiffreText);
		translateChiffre(chiffreText);
		return plainText;
	}
	
	private void initVariables() {
		this.key = "";
		this.periode = 0;
		this.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		this.plainText = "";
	}
	
	private void fetchPeriode(String chiffreText) {
		KasiskiTest kT = new KasiskiTest(chiffreText);
		int periode = kT.getKeyLength();
		this.periode = periode;
	}
	
	public LetterPair[] getFrequencyFromShiffre(String chiffreText, int startVal){
		String partChiffre = "";
		partChiffre = createPartChiffre(chiffreText, startVal);
		return new LetterFrequency(partChiffre).getSortedFrequency();
	}
	
	private String createPartChiffre(String chiffreText, int startValue) {
		String acc = "";
		int length = chiffreText.length() / periode;
		for (int i = 0; i < length; i++) {
			acc += chiffreText.charAt(startValue + i * periode);
		}
		return acc;
	}
		
	private void fetchKey(String chiffreText) {
		String acc = "";
		String partChiffre = "";
		for (int i = 0; i < periode; i++) {
			partChiffre = createPartChiffre(chiffreText, i);
			String mostFrequent = new LetterFrequency(partChiffre).getSortedFrequency()[0].getLetter();
			int offset = getOffset(mostFrequent);
			acc += getLetterFromIndex(offset);
		}
		key = acc;
	}
	
	private void translateChiffre(String chiffreText) {
		String plain = "";
		for (int j = 0; j < chiffreText.length(); j++) {
			char plainLetter = getLetterFromIndex(mod(chiffreText.charAt(j) - key.charAt(j % 5), 26));
			plain += plainLetter;
		}
		plainText = plain;
	}
			
	private int getOffset(String letter){
		return mod(letter.charAt(0) - 'E', 26);
	}
	
	private int mod(int val, int mod){
		int acc = val;
		while(acc < 0){
			acc += mod;
		}
		while(acc >= mod){
			acc -= mod;
		}
		return acc;
	}

	
	
	private char getLetterFromIndex(int index){
		return alphabet.charAt(index);
	}
		
	public void drawFrequency(String textChiffre, int frameX, int frameY){
		LetterPair[] sortedFreq = new LetterFrequency(textChiffre).getSortedFrequency();
		JFrame frame = new JFrame("Frequency");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(frameX + 50 , frameX + 50);
		Container cp = frame.getContentPane();
		JPanel histogramm = new VigenereDrawPanel(sortedFreq, frameX ,frameY);
		cp.add(histogramm);
		frame.setVisible(true);
	}
	
}
